package com.ton.system.controller;

import com.ton.config.annotation.Permission;
import com.ton.config.data.PermissionTreeVo;
import com.ton.system.entity.AdminPermission;
import com.ton.system.entity.AdminRole;
import com.ton.system.entity.AdminUser;
import com.ton.system.service.AdminUserService;
import com.ton.system.service.RoleService;
import com.hai.admin.table.vo.Result;
import com.ton.utils.AccessUtil;
import com.kypj.frame.common.EmptyUtil;
import com.kypj.frame.common.MD5Util;
import com.kypj.frame.db.Pager;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/admin")
@Api(value = "用户管理控制器",tags = "用户管理控制器")
public class AdminUserController {

    @Resource
    private AdminUserService adminUserService;

    @Resource
    private RoleService roleService;


	/*  @GetMapping("/export")
	@PermissionGuest
	public Result export(Pager pager){
	    Result result=new Result();
	    adminUserService.exportSql();
	    return  result;
	}*/


    @GetMapping("/user/list")
    @Permission("user:list")
    @ApiOperation(value = "获取用户列表",notes = "获取用户列表")
    public Result userList(Pager pager, String name) {
        Result result = new Result();
        List<AdminUser> list = adminUserService.listAdminUser(pager, name);
        result.addData("list", list);
        result.addData("pager", pager);
        return result;
    }

    @PostMapping("/edit/passwd")
    @ApiOperation(value = "修改密码",notes = "修改密码")
    public Result editPasswd(String oldPasswd, String newPasswd) {
        Result result = new Result();
        Integer userId = AccessUtil.getAdminLoginUserId();
        AdminUser adminUser = adminUserService.findAdminUserById(1);
        if (adminUser == null) {
            return result.setErrorMsg("请先登录");
        }
        if (newPasswd == null || newPasswd.length() < 5 || newPasswd.length() > 20) {
            return result.setErrorMsg("新密码长度必须5-20位");
        }
        if (!MD5Util.md5(oldPasswd).equals(adminUser.getPasswd())) {
            return result.setErrorMsg("旧密码输入有误");
        }
        adminUser.setPasswd(MD5Util.md5(newPasswd));
        adminUserService.updateAdminUser(adminUser);
        result.setSuccessMsg("密码修改成功");
        return result;
    }

    @GetMapping("/role/query")
    @ApiOperation(value = "角色查询",notes = "角色查询")
    public Result roleQuery(Integer adminId) {
        Result result = new Result();
        if (adminId != null) {
            List<AdminRole> adminRoles = roleService.listAdminRoleByUserId(adminId);
            result.addData("adminRoles", adminRoles);
            AdminUser user = adminUserService.findAdminUserById(adminId);
            result.addData("adminUser", user);
        }
        List<AdminRole> list = roleService.listAdminRole();
        result.addData("list", list);
        return result;
    }

    @GetMapping("/role/list")
    @ApiOperation(value = "获取角色列表",notes = "获取角色列表")
    public Result roleList(Pager pager, String name) {
        Result result = new Result();
        List<AdminRole> list = roleService.listAdminRole(pager, name);
        result.addData("list", list);
        result.addData("pager", pager);
        return result;
    }


    @GetMapping("/permission/tree/list")
    @ApiOperation(value = "获取权限信息",notes = "获取权限信息")
    public Result permissionList(Integer roleId) {

        Result result = new Result();
        if (roleId != null) {
            AdminRole role = roleService.findAdminRoleById(roleId);
            result.addData("role", role);
            List<AdminPermission> psList = roleService.listAdminPermission(roleId);
            result.addData("psList", psList);
        }
        List<AdminPermission> list = roleService.listAdminPermission();
        result.addData("list", PermissionTreeVo.createVo(list));
        return result;
    }

    @PostMapping("/change/status")
    @ApiOperation(value = "检查状态",notes = "检查状态")
    public Result changeStatus(Integer id, Integer flag) {
        Result result = new Result();
        AdminUser adminUser = adminUserService.findAdminUserById(id);
        if (adminUser.getLoginName().equals("admin")) {
            return result.setErrorMsg("不能对" + adminUser.getLoginName() + "用户执行此操作");
        }
        adminUserService.updateAdminUserFlag(id, flag);
        result.setSuccessMsg("操作成功");
        return result;
    }

    @PostMapping("/role/add")
    @Permission("role:add")
    @ApiOperation(value = "添加角色",notes = "添加角色")
    public Result add(Integer roleId, String roleName, String permissionIds) {
        Result result = new Result();
        if (roleId == null) {
            if (EmptyUtil.isEmpty(roleName) || roleName.length() < 2) {
                return result.setErrorMsg("角色名不能少于2位");
            }
            AdminRole temp = roleService.findAdminRoleByName(roleName);
            if (temp != null) {
                return result.setErrorMsg("角色名已经存在");
            }
            AdminRole role = new AdminRole();
            role.setRoleName(roleName);
            roleService.addAdminRole(role, permissionIds);
            result.setSuccessMsg("添加角色成功");
        } else {
            AdminRole role = roleService.findAdminRoleById(roleId);
            role.setRoleName(roleName);
            roleService.updateAdminRole(role, permissionIds);
            result.setSuccessMsg("修改角色成功");
        }
        return result;
    }

    @PostMapping("/role/del")
    @Permission("role:add")
    @ApiOperation(value = "删除角色",notes = "删除角色")
    public Result roleDel(Integer roleId) {
        Result result = new Result();
        AdminRole role = roleService.findAdminRoleById(roleId);
        if (role == null) {
            return result.setErrorMsg("角色已经不存在");
        }
        if (role.getRoleName().equals("超级管理员")) {
            return result.setErrorMsg("该角色不允许删除操作");
        }
        roleService.deleteAdminRole(roleId);
        result.setSuccessMsg("角色删除成功");
        return result;
    }


    @PostMapping("/edit/user/passwd")
    @Permission("user:add")
    @ApiOperation(value = "修改用户密码",notes = "修改用户密码")
    public Result editUserPasswd(String newPasswd, Integer userId) {
        Result result = new Result();
        AdminUser adminUser = adminUserService.findAdminUserById(userId);
        if (adminUser == null) {
            return result.setErrorMsg("用户不存在");
        }
        if (newPasswd == null || newPasswd.length() < 5 || newPasswd.length() > 20) {
            return result.setErrorMsg("新密码长度必须5-20位");
        }
        adminUser.setPasswd(MD5Util.md5(newPasswd));
        adminUserService.updateAdminUser(adminUser);
        result.setSuccessMsg("密码重置成功");
        return result;
    }

    @PostMapping("/user/add")
    @Permission("user:add")
    @ApiOperation(value = "添加用户",notes = "添加用户")
    public Result add(Integer id, String personName, String loginName, String passwd
            , String mobile, String adminRoleIds, Integer maxDevice) {
        Integer proxyUserId = null;
        Result result = new Result();
        if (EmptyUtil.isEmpty(loginName) || loginName.length() < 3) {
            return result.setErrorMsg("登录名不能少于3位");
        }
        if (maxDevice == null) {
            maxDevice = 1;
        }
        if (id == null) {
            if (EmptyUtil.isEmpty(passwd) || passwd.length() < 6) {
                return result.setErrorMsg("密码不能少于6位");
            }
            AdminUser temp = adminUserService.findAdminUserByLoginName(loginName);
            if (temp != null) {
                return result.setErrorMsg("登录名已经存在");
            }
            AdminUser user = new AdminUser();
            user.setCreateTime(new Date());
            user.setFlag(0);
            user.setLoginName(loginName);
            user.setMobile(mobile);
            user.setPasswd(MD5Util.md5(passwd));
            user.setPersonName(personName);
            user.setMaxDevice(maxDevice);
            user.setProxyUserId(proxyUserId);
            adminUserService.addAdminUser(user, adminRoleIds);
            result.setSuccessMsg("添加用户成功");
        } else {
            AdminUser user = adminUserService.findAdminUserById(id);
            //user.setLoginName(loginName);
            user.setMobile(mobile);
            user.setPersonName(personName);
            user.setMaxDevice(maxDevice);
            user.setProxyUserId(proxyUserId);
            adminUserService.updateAdminUser(user, adminRoleIds);
            result.setSuccessMsg("修改用户成功");
        }
        return result;
    }

    @GetMapping("/permission/getAdminPermission")
    @ApiOperation(value = "获取管理员权限",notes = "获取管理员权限")
    public Result getAdminPermission(String uri) {

        Result result = new Result();
        if (uri != null) {
            AdminPermission adminPermission = roleService.getAdminPermission(uri);
            if (Objects.isNull(adminPermission)) {
                result.setErrorMsg("数据为空，跳转失败");
                result.setCode(500);
                return result;
            }
            result.addData("adminPermission", adminPermission);
            return result;
        }
        result.setErrorMsg("数据为空，跳转失败");
        result.setCode(500);
        return result;
    }
}
